package com.guqj.thread.concurrent.syntool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class SemaphoreTest {

	public static void main(String[] args) {
		ExecutorService executor = Executors.newFixedThreadPool(2);
		final Semaphore sema = new Semaphore(5, false);
		for (int i = 0; i < 100; i++) {
			final int num = i;
			executor.execute(new Runnable() {
				@Override
				public void run() {
					try {
						sema.acquire();
						System.out.println("线程" + Thread.currentThread().getName() + "获得许可：" + num);
						Thread.sleep(2000);
						// 释放许可
						sema.release();
						System.out.println("线程" + Thread.currentThread().getName() + "释放许可：" + num);
						System.out.println("当前允许进入的任务个数：" + sema.availablePermits());
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			});
		}
		executor.shutdown();
	}
}
